//浏览器的WebSocket客户端
function WSClient(uri, short) {
	this.uri = uri;
	this.state = 0;
	this.short = short;
	this.connect = function(connectCallback, errorCallback, recvCallback, closeCallback) {
		if ("WebSocket" in window) {
			this.ws = new WebSocket(this.uri);
			// this.ws.binaryType = "arraybuffer";
			this.state = 1;
			let self = this;
			this.ws.onopen = function() {
				self.state = 2;
				if(connectCallback) {
					connectCallback();
				}
			};
			this.ws.onmessage = function (evt) {
				if(recvCallback) {
					recvCallback(evt.data);
				}
				if (self.short) {
					setTimeout(() => {
						self.close();
					}, 300);
				}
			};
			this.ws.onclose = function() {
				self.state = 0;
				if(closeCallback) {
					closeCallback();
				}
			};
			this.ws.onerror = function(err) {
				if(errorCallback) {
					errorCallback(err);
				}
			};
		} else {
			alert("您的浏览器不支持 WebSocket!");
		}
	};
	this.send = function(data) {
		if(this.state==2) {
			this.ws.send(data);
		}
	};
	this.close = function() {
		if (this.state>0) {
			this.ws.close();
			this.ws = null;
			this.state = 0;
		}
	};
}

function makeWebSocket(uri, data, recv) {
	let ws = new WSClient(uri, true);
	ws.connect(function() {
		ws.send(data);
	}, function(err) {
		console.error("websocket error!");
	}, recv, null);
}
